import express from 'express'
import { Response, Request } from "express"

const router = express.Router()

import { success, failure } from '../utils/responses'
import { AppDataSource } from "../config/database";
import { User } from "../entities/User";
import { AuthRequest } from "../middlewares/user-auth";
import { BadRequest } from "http-errors";
import { filterUser } from "./users";

/**
 * 加关注、取消关注
 */
router.post('/', async function (req: Request, res: Response) {
  try {
    // 拿到关注者id
    const followingId = req.body.followingId as string
    const userRepository = AppDataSource.getRepository(User)

    const followingUser = await userRepository.findOneBy({ id: followingId }) // 用户主动关注的对象
    if (!followingUser) throw new BadRequest('关注对象不存在')

    const userId = (req as AuthRequest).id
    const user = await userRepository.findOne({
      where: { id: userId },
      relations: { followings: true } // 必须要加载followings，否则user实体没有followings字段
    }) // 当前登录的用户

    const userIndex = user.followings.findIndex(item => item.id === followingId)
    if (userIndex !== -1) {
      // 找到了，说明已经关注过，应取消关注
      user.followings.splice(userIndex, 1)
      await userRepository.save(user)
      success(res, '取消关注成功')
    } else {
      // 没找到，说明没有关注过，应关注
      user.followings.push(followingUser) // 将关注者添加到当前用户的关注列表中
      await userRepository.save(user)
      success(res, '关注成功')
    }
  } catch (error) {
    failure(res, error)
  }
})

/**
 * 查询用户关注列表
 */
router.get('/', async function (req: Request, res: Response) {
  try {
    const userId = (req as AuthRequest).id as string
    const userRepository = AppDataSource.getRepository(User)
    // 获取当前登录用户
    const user = await userRepository.findOne({
      where: { id: userId },
      relations: { followings: true } // 必须要加载followings，否则user实体没有followings字段
    })
    // 过滤关注者的信息
    const followingsList = user.followings.map(following => filterUser(following))
    success(res, '查询关注列表成功', followingsList)
  } catch (error) {
    failure(res, error)
  }
})

/**
 * 查询用户是否关注
 */
router.get('/:followingId', async function (req: Request, res: Response) {
  try {
    const followingId = req.params.followingId
    const userRepository = AppDataSource.getRepository(User)

    const userId = (req as AuthRequest).id
    const user = await userRepository.findOne({
      where: { id: userId },
      relations: { followings: true } // 必须要加载followings，否则user实体没有followings字段
    })

    const userIndex = user.followings.findIndex(item => item.id === followingId)
    if (userIndex !== -1) {
      // 找到，说明已经关注过
      success(res, '成功查询关注状态', { isFollowing: true })
    } else {
      // 没找到，说明没有关注过
      success(res, '成功查询关注状态', { isFollowing: false })
    }
  } catch (error) {
    failure(res, error)
  }
});


export default router
